package com.code.controller;

import com.code.entity.User;
import com.code.service.IUserService;
import com.code.util.RSAUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping(value = "/login")
@Slf4j
@ApiOperation(value = "登录",notes = "登录")
public class LoginController {

    @Autowired
    private IUserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/to/toLoginIndex")
    @ApiOperation(value = "跳转到登录界面",notes = "跳转到登录界面")
    public String toLoginIndex(Model model, HttpServletRequest request, HttpServletResponse response){
        return "login/login";
    }

    @ApiOperation(value = "登录",notes = "登录")
    @PostMapping(value = "/getLogin",produces = "text/html;charset=utf-8")
    public String getLogin(Model model, HttpServletRequest request, HttpServletResponse response, User user) throws Exception,JsonProcessingException {
        //声明 redisTemplate
        ValueOperations ops = redisTemplate.opsForValue();
        //获取用户名 、 密码
        String username = user.getUsername();
        String password = user.getPassword();

        //获取password 先进性解密
        String pass =  RSAUtil.getMd5(password);
       //校验用户名和密码是否已经存在
        User userResult  = userService.checkedUserAndPass(username, pass);
        if(userResult != null){
            String s = UUID.randomUUID().toString();
            ObjectMapper om = new ObjectMapper();
            userResult.setToken(s);
            ops.set(s,om.writeValueAsString(userResult));//将凭证存入Redis
            redisTemplate.expire(s,5,TimeUnit.MINUTES);//设置过期时间，30分钟
            response.setHeader("token",s);
            request.getSession().setAttribute("token",s);
            return "redirect:/user/to/toUserIndex";
        }else{
            return "redirect:/login/to/toLoginIndex";
        }
    }

    @ApiOperation(value = "登出",notes = "登出")
    @GetMapping(value = "/logOut")
    public String logOut( HttpServletResponse response,HttpServletRequest request){
        String token = (String)request.getSession().getAttribute("token");
        redisTemplate.delete(token);
        request.getSession().removeAttribute(token);
        return "redirect:/";
    }


}
